package com.xxx.common.base.util;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class BuilderUtil<T> {

    private Supplier<T> createInstance;
    private List<Consumer<T>> consumers;

    private BuilderUtil() {
    }

    public static <T> BuilderUtil<T> of(Supplier<T> constructor) {
        BuilderUtil<T> instance = new BuilderUtil<>();
        instance.createInstance = constructor;
        instance.consumers = new ArrayList<>(8);
        return instance;
    }

    public <P> BuilderUtil<T> set(BiConsumer<T, P> consumer, P p) {
        this.consumers.add((instance) -> {
            consumer.accept(instance, p);
        });
        return this;
    }

    public T build() {
        T t = this.createInstance.get();

        for (Consumer<T> consumer : this.consumers) {
            consumer.accept(t);
        }

        return t;
    }

}
